<template>
  <page-dialog
    :title="dialogInfo.title"
    v-model:visible="shows"
    :width="dialogInfo.width"
    :bt-list="dialogInfo.btList"
  >
    <div class="left-container-header border-style-bottom">
      <el-input
        style="width: 200px; margin-left: 10px"
        v-model="filterInfo.query.deptName"
        :clearable="true"
        placeholder="请输入部门名称"
        @keyup.enter="getList"
      >
      </el-input>
      <el-input
        style="width: 200px; margin-left: 10px"
        v-model="filterInfo.query.userName"
        :clearable="true"
        placeholder="请输入员工名称"
        @keyup.enter="getList"
      >
      </el-input>
      <el-button :plain="true" @click="getList">搜索</el-button>
    </div>
    <div class="side_scroll_y">
      <el-tree
        class="eltree"
        ref="tree"
        :data="treeInfo.data"
        highlight-current
        :props="treeInfo.defaultProps"
        node-key="id"
        show-checkbox
        :default-checked-keys="treeInfo.checked"
        @check="checkFn"
        @check-change="checkChange"
        @node-click="nodeCheck"
        :default-expand-all="false"
        :check-strictly="!multiple"
        :expand-on-click-node="false"
        :default-expanded-keys="treeInfo.ids"
        :query="filterInfo.query"
      />
    </div>
  </page-dialog>
</template>

<script setup name="SelectDeptUserTrees">
// 部门人员树
import PageDialog from '../PageDialog/index'
import PageFilter from '../PageFilter/index'
import { deptUserTrees } from '@/api/core.js'
const emits = defineEmits()
const { proxy } = getCurrentInstance()
const props = defineProps({
  showDialog: {
    type: Boolean,
    default: false,
  },
  checkedKeys: {
    type: Array,
    default: function () {
      return []
    },
  },
  multiple: {
    type: Boolean,
    default: true,
  },
})

// 过滤相关配置
const filterInfo = ref({
  query: {
    deptName: '',
    userName: '',
  },
  list: [
    // {type: 'input', label: '部门名称', value: 'deptName'},
    // {type: 'input', label: '员工名称', value: 'userName'},
    // {type: 'button', label: '搜索', event: getList}
  ],
})
// 弹窗相关
const dialogInfo = ref({
  title: '人员选择',
  btLoading: false,
  btList: [
    { label: '关闭', event: handleClose, show: true },
    {
      label: '保存',
      type: 'primary',
      disabled: true,
      event: save,
      show: true,
    },
  ],
  width: '800px',
})
const treeInfo = ref({
  data: [],
  nodeKey: 'code',
  checked: [],
  ids: [-1],
  defaultProps: {
    children: 'children',
    label: 'name',
  },
  selectNode: [],
})
const editCheckId = ref(undefined)

const shows = computed({
  get() {
    return props.showDialog
  },
  set(newValue) {
    emits('update:showDialog', newValue) // 更新父组件shows
  },
})

onMounted(() => {
  // hack, 在table创建出来之后再去调用
  proxy.$nextTick(() => {
    getList()
    treeInfo.value.checked = [...props.checkedKeys]
    setTimeout(() => {
      let arr = proxy.$refs.tree.getCheckedNodes()
      arr = arr.filter((item) => !item.disabled)
      treeInfo.value.selectNode = arr
    }, 500)
    dialogInfo.value.btList[1].disabled = !props.checkedKeys.length
  })
})

// 获取列表
function getList() {
  let params = filterInfo.value.query
  deptUserTrees(params).then((res) => {
    if (res.success) {
      treeInfo.value.data = res.data
      if (treeInfo.value.selectNode.length) {
        let ids = []
        treeInfo.value.selectNode.forEach((item) => {
          ids.push(item.id)
        })
        proxy.$refs.tree.setCheckedKeys(ids)
      }
      disabledFn().filter(treeInfo.value.data)
    }
  })
}
function disabledFn() {
  let resultArr = new Array()
  let getTickMenuId = function (obj) {
    if (undefined == obj || null == obj || !(obj instanceof Object)) {
      return
    }
    if (obj.type === 'menu') {
      if (obj.children.length === 0) {
        obj.children.push({ disabled: true })
      }
      obj.disabled = true
      resultArr.push(obj.id)
    } else if (obj.type === 'user') {
      treeInfo.value.ids.push(obj.id)
    }
    if (null != obj.children && obj.children instanceof Array) {
      for (let child of obj.children) {
        getTickMenuId(child)
      }
    }
  }
  return {
    filter: function (arr) {
      if (!(arr instanceof Array)) {
        return false
      }
      resultArr = new Array()
      for (let rootMenu of arr) {
        getTickMenuId(rootMenu)
      }
      return resultArr
    },
  }
}
// 关闭弹窗前的回调
function handleClose() {
  shows.value = false
  emits('reset')
}
function save() {
  if (treeInfo.value.selectNode) {
    handleClose()
    emits('callback', treeInfo.value.selectNode)
  }
}
function checkFn(node, data) {
  if (props.multiple) {
    let findIndex = data.checkedNodes.findIndex((el) => el.id === node.id)
    dialogInfo.value.btList[1].disabled = !node
    if (data.checkedNodes.length) {
      if (findIndex > -1) {
        treeInfo.value.selectNode.push(node)
      } else {
        treeInfo.value.selectNode = treeInfo.value.selectNode.filter((item) => {
          return item.id !== node.id
        })
      }
    } else {
      treeInfo.value.selectNode = treeInfo.value.selectNode.filter((item) => {
        return item.id !== node.id
      })
    }
  }

  // let currKey = [];
  // data.checkedNodes.filter((item)=>{
  //     currKey.push(item.id)
  // })
  // proxy.$refs.tree.setCheckedKeys(currKey);
}
function checkChange(item, node, self) {
  if (!props.multiple) {
    // treeInfo.value.checked = [item.id]
    if (node === true) {
      editCheckId.value = item.id
      proxy.$refs.tree.setCheckedKeys([item.id])
      dialogInfo.value.btList[1].disabled = !item.id
      treeInfo.value.selectNode = [item]
    } else {
      if (editCheckId.value === item.id) {
        proxy.$refs.tree.setCheckedKeys([])
        treeInfo.value.selectNode = []
      }
    }
  }
}
function nodeCheck(item, node, self) {
  let checkedKeys = proxy.$refs.tree.getCheckedKeys(true)
  let findIndex = checkedKeys.findIndex((el) => el === item.id)
  console.log(findIndex, item, !item.id, 'findIndex')
  if (item.type === 'user') {
    if (!props.multiple) {
      if (findIndex === -1) {
        editCheckId.value = item.id
        proxy.$refs.tree.setCheckedKeys([item.id])
        dialogInfo.value.btList[1].disabled = !item.id
        treeInfo.value.selectNode = [item]
      } else {
        proxy.$refs.tree.setCheckedKeys([])
        treeInfo.value.selectNode = []
      }
    } else {
      editCheckId.value = item.id
      let checkedKeys = proxy.$refs.tree.getCheckedKeys(true)
      let findIndex = checkedKeys.findIndex((el) => el === item.id)
      if (findIndex === -1) {
        proxy.$refs.tree.setChecked(item.id, true)
        treeInfo.value.selectNode.push(item)
      } else {
        proxy.$refs.tree.setChecked(item.id, false)
        treeInfo.value.selectNode.splice(findIndex, 1)
      }
      dialogInfo.value.btList[1].disabled = !item.id
    }
  }
}
</script>

<style lang="scss">
.eltree {
  .el-tree-node {
    .is-leaf + .el-checkbox .el-checkbox__inner {
      display: inline-block;
    }
    .el-checkbox__input > .el-checkbox__inner,
    .is-disabled {
      display: none;
    }
  }
}
</style>
